package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.media.dto.*;
import com.heima.media.entity.*;
import com.heima.media.feign.ArticleFeign;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.media.service.IWmUserService;
import org.apache.commons.io.IOUtils;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RQueue;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-15
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    @Lazy    // 解决循环依赖问题
    private IAuditService auditService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.upDownTopic}")
    private String upDownTopic;

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    private IWmUserService wmUserService;

    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {

        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();

        if (dto.getStatus() != null) {

            query.eq(WmNews::getStatus, dto.getStatus());
        }

        if (dto.getKeyword() != null) {

            query.like(WmNews::getTitle, dto.getKeyword());
        }

        if (dto.getChannelId() != null) {

            query.eq(WmNews::getChannelId, dto.getChannelId());
        }

        if (dto.getBeginPubDate() != null) {
            query.gt(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        if (dto.getEndPubDate() != null) {
            query.lt(WmNews::getPublishTime, dto.getEndPubDate());
        }

        User user = MediaThreadLocalUtil.get();

        if (user == null) {

            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        query.eq(WmNews::getUserId, user.getUserId());

        query.orderByDesc(WmNews::getPublishTime);

        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        IPage<WmNews> page1 = this.page(page, query);

        return new PageResponseResult(dto.getPage(), dto.getSize(), page1.getTotal(), page1.getRecords());
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {

        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (dto.getId() != null) {

            deleteRelation(dto.getId());
        }
        WmNews wmNews = new WmNews();

        BeanUtils.copyProperties(dto, wmNews);

        wmNews.setUserId(user.getUserId());

        wmNews.setCreatedTime(new Date());

        wmNews.setImages(JSON.toJSONString(dto.getImages()));

        List<ImageDto> contentImages = getImagesFromContent(dto.getContent());

        if (dto.getType() == -1) {

            int size = contentImages.size();

            if (size <= 0) {

                wmNews.setType(0);

            } else if (size < 3) {

                wmNews.setType(1);

                ImageDto imageDto = contentImages.get(0);

                List<ImageDto> list = new ArrayList<>();

                list.add(imageDto);

                wmNews.setImages(JSON.toJSONString(list));
            } else {

                wmNews.setType(3);

                List<ImageDto> list = contentImages.subList(0, 3);

                wmNews.setImages(JSON.toJSONString(list));
            }
        }
        this.saveOrUpdate(wmNews);

        if (dto.getStatus() != 0) {

            List<ImageDto> list = JSON.parseArray(wmNews.getImages(), ImageDto.class);

            saveRelation(list, 1, wmNews.getId());
            // 关联内容中的图片
            saveRelation(contentImages, 0, wmNews.getId());

            System.out.println(Thread.currentThread().getName() + " 调用自动审核服务...");

            auditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {

        WmNews wmNews = this.getById(dto.getId());

        if (wmNews == null) {

            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmNews.getStatus() != 9) {

            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_UPDATE);
        }

        wmNews.setEnable(dto.getEnable() == 1 ? true : false);

        this.updateById(wmNews);

        kafkaTemplate.send(upDownTopic, wmNews.getArticleId().toString(), (dto.getEnable() == 1) ? "false" : "true");

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult selectWmNews(NewsAuthDto wmNewsSelectDto) {

        System.out.println("标题内容是：" + wmNewsSelectDto.getTitle());

        if (wmNewsSelectDto == null) {

            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        if (wmNewsSelectDto.getPage() == null) {

            wmNewsSelectDto.setPage(1L);
        }

        if (wmNewsSelectDto.getSize() == null) {

            wmNewsSelectDto.setPage(10L);
        }
        //   System.out.println("文章标题是：" + wmNewsSelectDto.getMsg());
        LambdaUpdateWrapper<WmNews> query = new LambdaUpdateWrapper<>();

        if (wmNewsSelectDto.getMsg() != null) {

            query.like(WmNews::getTitle, wmNewsSelectDto.getTitle());
        }

        if (wmNewsSelectDto.getStatus() != null) {

            query.eq(WmNews::getStatus, wmNewsSelectDto.getStatus());
        }
        query.orderByDesc(WmNews::getCreatedTime);

        IPage<WmNews> page = new Page<>(wmNewsSelectDto.getPage(), wmNewsSelectDto.getSize());

        IPage<WmNews> page1 = this.page(page, query);

        List<WmNews> records = page1.getRecords();

        for (WmNews record : records) {

            //   System.out.println("文章id是："+record.getArticleId());

            WmUser byId = wmUserService.getById(record.getUserId());

            ResponseResult<ApAuthor> authorById = articleFeign.getAuthorById(byId.getApAuthorId());

            record.setAuthorName(authorById.getData().getName());

            //    System.out.println("--------记录是：" + records);
        }
        return new PageResponseResult(wmNewsSelectDto.getPage(), wmNewsSelectDto.getSize(), page1.getTotal(), records);
    }

    @Override
    public ResponseResult getDetails(Integer id) {

        if (id == null) {

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews byId = this.getById(id);

        if (byId != null) {

            WmUser byId1 = wmUserService.getById(byId.getUserId());

            ResponseResult<ApAuthor> authorById = articleFeign.getAuthorById(byId1.getApAuthorId());

            byId.setAuthorName(authorById.getData().getName());

            return ResponseResult.okResult(byId);
        }
        return null;
    }

    @Override
    public ResponseResult getExamine(NewsAuthDto dto) {

        if (dto == null) {

            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaUpdateWrapper<WmNews> update = new LambdaUpdateWrapper<>();

        update.eq(WmNews::getId, dto.getId());

        update.set(WmNews::getReason, dto.getMsg());

        update.set(WmNews::getStatus,2);

        this.update(update);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getSuccessExamine(NewsAuthDto dto) {

        if (dto == null) {

            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews one = this.getById(dto.getId());

        one.setStatus(4);

        LambdaUpdateWrapper<WmNews> update = new LambdaUpdateWrapper<>();

        update.set(WmNews::getStatus,4);

        update.eq(WmNews::getId, dto.getId());

        this.update(update);

        auditService.audit(one);

        return ResponseResult.okResult();
    }
    @Autowired
    IWmNewsMaterialService wmNewsMaterialService;

    private void saveRelation(List<ImageDto> list, int type, int newsId) {

        int ord = 0;

        for (ImageDto imageDto : list) {

            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();

            wmNewsMaterial.setMaterialId(imageDto.getId());

            wmNewsMaterial.setType(type);

            wmNewsMaterial.setNewsId(newsId);

            wmNewsMaterial.setOrd(ord++);

            wmNewsMaterialService.save(wmNewsMaterial);
        }
    }

    private List<ImageDto> getImagesFromContent(String content) {

        List<ImageDto> list = new ArrayList<>();

        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);

        for (ContentDto contentDto : contentDtos) {

            if (contentDto.getType().equals("image")) {

                ImageDto imageDto = new ImageDto();

                imageDto.setId(contentDto.getId());

                imageDto.setUrl(contentDto.getValue());

                list.add(imageDto);
            }
        }
        return list;
    }

    private void deleteRelation(Integer id) {

        LambdaQueryWrapper<WmNewsMaterial> query = new LambdaQueryWrapper<>();

        query.eq(WmNewsMaterial::getNewsId, id);

        wmNewsMaterialService.remove(query);
    }
}
